<template>
<div>
   <el-checkbox-group v-model="defaultValue" @change="handleChange">
      <div v-for="checkboxs in checkboxList" :key="checkboxs.index">
         <el-checkbox  v-for="checkbox in checkboxs.data" :label="checkbox.bm" :key="checkbox.bm" :style="checkboxStyle">{{checkbox.mc}}</el-checkbox>
      </div>
  </el-checkbox-group>
</div>
</template>

<script>
import { query } from '@/api/common'

export default {
  name: 'defCheckboxGroup',
  data() {
    return {
      defaultValue: [],
      checkboxList: []
    }
  },
  props: {
    value: {
      type: Array
    },
    url: {
      type: String
    },
    sortNum: {// 复选框一行个数 默认三个
      type: Number,
      required: false,
      default: 3
    },
    queryparam: {
      type: Object,
      required: false,
      default: function() {
        return {}
      }
    },
    checkboxStyle: {
      type: Object,
      required: false,
      default: function() {
        return { width: '350px' }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    handleChange(val) {
      this.$emit('input', val)
    },
    init() {
      query(this.url, this.queryparam).then((result) => {
        const allCheckList = result.data.data
        if (allCheckList) {
          let index = 0
          let checkboxOfDiv = []
          const checkSize = allCheckList.length
          allCheckList.forEach(check => {
            index++
            checkboxOfDiv.push(check)
            if (index === checkSize) {
              this.checkboxList.push({
                index: index,
                data: checkboxOfDiv
              })
            } else if (index % this.sortNum === 0) {
              this.checkboxList.push({
                index: index,
                data: checkboxOfDiv
              })
              checkboxOfDiv = []
            }
          })
        }
      })
    }
  },
  watch: {
    value() {
      this.defaultValue = this.value
    }
  }
}
</script>